package middlewere

import (
	"Gin/global/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
)

func LoginMiddlewere() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("token")
		if token == "" {
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code": 400,
				"msg":  "未登录",
			})
			return
		}
		data, err := pkg.TokenData(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"status": http.StatusUnauthorized,
				"msg":    "登录失效",
			})
			return
		}
		user_id := data["user"].(float64)
		set, _ := json.Marshal(int64(user_id))
		c.Request.ParseForm()
		c.Request.Form.Set("UserId", string(set))
		c.Next()
	}
}
